# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Utility interfaces to calling svn diff

Simple interfaces to isolate calls to the svn diff command.  The first
handles all the ways that you can specify an external command and includes
the options in the svn diff command, while the second provides only the
first n lines of diff output.
"""


import gvn.changebranch
import gvn.svncmd


def RunSvnDiff(options, config, args):
  """Run svn diff args, inserting --diff-cmd and --extensions arguments
  if an external diff program is specified.

  """

  svn_args = ['diff']
  diff_cmd = config.diff_command
  # TODO(epg): Fix up, generalize, and use diff stuff from
  # changebranch.py so we can use tkdiff.
  if diff_cmd is not None and diff_cmd != 'internal':
    diff_cmd_parts = diff_cmd.split(None, 1)
    svn_args.extend(['--diff-cmd', diff_cmd_parts[0]])
    if len(diff_cmd_parts) > 1:
      svn_args.extend(['--extensions', diff_cmd_parts[1]])
  svn_args.extend(args)
  return gvn.svncmd.RunSvn(svn_args, options=options)

def GetShortDiff(project, cb, pool):
  """Return up to project.Difflines of the ChangeBranch cb's diff.

  Return value is a tuple of the diff (as a str) and an estimate of the number
  of changed lines in the diff.

  """

  class truncate(Exception):
    pass

  shortdiff = []
  class DiffReader(object):
    def write(self, line):
      if len(shortdiff) < project.diff_lines:
        shortdiff.append(line)
        return
      raise truncate
  fp = DiffReader()
  try:
    gvn.changebranch.Diff(project.repository, cb, fp, 'internal', pool=pool)
  except truncate:
    shortdiff.append('\n*** TRUNCATED TO %d lines ***\n'
                     % (project.diff_lines,))

  # Unified diffs: lines starting with + or - are changes.
  changed_lines = [x for x in shortdiff if x[0] in ('+', '-')]
  return (''.join(shortdiff).decode('utf-8'), len(changed_lines))

